using MediatR;
using SumerCoreDevOps.Application.Statistics.Queries;
using SumerCoreDevOps.Domain.Entities;
using SumerCoreDevOps.Infrastructure.Data;
using SumerCoreDevOps.Shared.Models;
using TaskStatus = SumerCoreDevOps.Shared.Enums.TaskStatus;

namespace SumerCoreDevOps.Application.Statistics.Handlers;

/// <summary>
/// 获取任务状态分布处理器
/// </summary>
public class GetTaskStatusDistributionQueryHandler : IRequestHandler<GetTaskStatusDistributionQuery, TaskStatusDistribution>
{
    private readonly FreeSQLProvider _dbProvider;

    public GetTaskStatusDistributionQueryHandler(FreeSQLProvider dbProvider)
    {
        _dbProvider = dbProvider;
    }

    public async Task<TaskStatusDistribution> Handle(GetTaskStatusDistributionQuery request, CancellationToken cancellationToken)
    {
        // 获取所有任务
        var tasks = await _dbProvider.Orm.Select<TaskEntity>()
            .ToListAsync(cancellationToken);

        return new TaskStatusDistribution
        {
            Pending = tasks.Count(t => t.Status == TaskStatus.Pending),
            Running = tasks.Count(t => t.Status == TaskStatus.Running),
            Success = tasks.Count(t => t.Status == TaskStatus.Success),
            Failed = tasks.Count(t => t.Status == TaskStatus.Failed),
            Cancelled = tasks.Count(t => t.Status == TaskStatus.Cancelled)
        };
    }
}
